<?php

require_once 'Classes/Loan.php';
require_once 'Classes/Model/PDOModel.php';

class LoanModel extends PDOModel implements Singleton {
    
    
     private static $instance;
     
     public function getInstance(){
        if (!isset(self::$instance)) {
            $c = __CLASS__;
            self::$instance = new $c;
        }

        return self::$instance;
     }
     
     public function __clone() {
         throw new Exception("You may not try to clone this object");
     }
 
    protected function __construct() {
        parent::__construct();
    }
    
    
    public function addLoan($loan) {
        $value = array($loan->getStatut(), $loan->getStartingDate(), $article->getEndingDate(), $article->getUserID());

        $this->PDORequest('INSERT INTO Loans (Statut, Starting_Date, Ending_Date, UserID) VALUES (?, ?, ?, ?)', $value);
                
    }
    
    public function updateLoan($loan) {
        $value = array($loan->getStatut(), $loan->getStartingDate(), $article->getEndingDate(), $article->getUserID(), $loan->getId());
        
        $this->PDORequest('UPDATE Loans SET Statut=?, Starting_Date=?, Ending_Date=?, UserID=? WHERE ID=?', $value);
  
    }

    public function getAllLoans() {
        $result = $this->PDORequest('SELECT * FROM Loans');
           
        if($result) {
            $arr = array();
            foreach ($result as $loan) {
                array_push($arr, new Loan($loan));
            }
            return $arr;
        }
    }
    
    public function getDetailedLoanById($id) {
        $value = array($id);
        $result = $this->PDORequest('SELECT Statut , Starting_Date , Ending_Date, ClientID,  
        (SELECT First_Name FROM Clients WHERE Clients.ID = Loans.ClientID) AS Client_First_Name, 
        (SELECT Last_Name FROM Clients WHERE Clients.ID = Loans.ClientID) AS Client_Last_Name, 
        (SELECT Phone FROM Clients WHERE Clients.ID = Loans.ClientID) AS Client_Phone, 
        (SELECT Function FROM Clients WHERE Clients.ID = Loans.ClientID) AS Client_Function, 
        (SELECT Address FROM Clients WHERE Clients.ID = Loans.ClientID) AS Client_Address,
        (SELECT Name FROM Structures WHERE Structures.ID = (SELECT ID FROM Clients WHERE Clients.ID = Loans.ClientID)) AS Client_Structure
        FROM Loans WHERE  ID =  ? ORDER BY Starting_Date DESC', $value);
        return new Loan($result[0]);
    }
        
        public function getArticleofLoanById($id) {
        $value = array($id);
        $result = $this->PDORequest('SELECT BarCode, Name, COUNT(BarCode) AS Quantity 
        FROM Articles WHERE ID = ? GROUP BY BarCode', $value);
        return new Loan($result[0]);
    }
	
	
	public function deleteLoanById($id){
	    $sql="DELETE FROM Loan WHERE ID = ?";
	    $this->PDORequest($sql,array($id));
	}
}

?>
